package com.tcm.pay.common;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * @Description: AES 加/解密相关
 * @Author:xgchen
 * @Date:2016-07-11 15:58
 * @Version:V0.0.1
 */
public class AESEncrypt {

    private static final String ALGORITHM = "AES";
    /**
     * "算法/模式/补码方式"
     */
    private static final String AES_ECB_PKCS5_PADDING = "AES/ECB/PKCS5Padding";

    public static String generateAESKey() throws Exception {
        //KeyGenerator提供对称密钥生成器的功能，支持各种算法
        KeyGenerator keygen = KeyGenerator.getInstance(ALGORITHM);
        //SecretKey负责保存对称密钥
        keygen.init(128);
        String key = Base64.encodeBase64String(keygen.generateKey().getEncoded());
        return key;
    }

    /**
     * AES ecb加密
     *
     * @param content
     * @param key
     * @return
     * @throws Exception
     */
    public static String encryptECB(String content, String key) throws Exception {
        SecretKeySpec keySpec = new SecretKeySpec(Base64.decodeBase64(key.getBytes()), ALGORITHM);
        Cipher cipher = Cipher.getInstance(AES_ECB_PKCS5_PADDING);
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        byte[] encryptBytes = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
        return Base64.encodeBase64String(encryptBytes);
    }

    /**
     * AES ecb解密
     *
     * @param content 密文
     * @param key     aes秘钥
     * @return
     * @throws Exception
     */
    public static String decryptECB(String content, String key) throws Exception {
        SecretKeySpec keySpec = new SecretKeySpec(Base64.decodeBase64(key.getBytes()), ALGORITHM);
        Cipher deCipher = Cipher.getInstance(AES_ECB_PKCS5_PADDING);
        deCipher.init(Cipher.DECRYPT_MODE, keySpec);
        byte[] bytes = deCipher.doFinal(Base64.decodeBase64(content.getBytes(StandardCharsets.UTF_8)));
        return new String(bytes, StandardCharsets.UTF_8);
    }

}
